import React, { useEffect, useRef, useState } from "react";
import { Card, Col, Row, List, Avatar, Drawer } from "antd";
import {
  EditOutlined,
  EllipsisOutlined,
  SettingOutlined,
} from "@ant-design/icons";
import axios from "axios";
import * as Echarts from "echarts"; //导入echarts
import _ from "lodash"; //使用lodash

const { Meta } = Card;
export default function Home() {
  const [viewList, setViewList] = useState([]); //最常浏览的数据
  const [startList, setStartList] = useState([]); //请求点赞最多的
  const [allList, setAllList] = useState([]); //饼图数据
  const [open, setOpen] = useState(false); //抽屉显示隐藏
  const barRef = useRef(null); //柱状图的ref
  const pieRef = useRef(null); //饼图的ref
  const [pieChart, setPieChart] = useState(null);
  // 请求最常浏览的数据
  /*
  desc是倒序的 _limit拿回最多的条数
  */
  useEffect(() => {
    axios
      .get(
        `/news?publishState=2&_expand=category&_sort=view&_order=desc&_limit=6`
      )
      .then((res) => {
        // console.log(res.data)
        setViewList(res.data);
      });
  }, []);
  // 请求点赞最多的
  useEffect(() => {
    axios
      .get(
        `/news?publishState=2&_expand=category&_sort=star&_order=desc&_limit=6`
      )
      .then((res) => {
        setStartList(res.data);
      });
  }, []);
  // echarts使用
  useEffect(() => {
    axios.get(`/news?publishState=2&_expand=category`).then((res) => {
      //   console.log(res.data)
      // 把res.data中的数据，以里面每一个成员的category.label为基础进行分组
      //_.groupBy(第一个参数是会进行一个排序，第二个参数是会进一个分组)方法
      renderBarView(_.groupBy(res.data, (item) => item.category.label));
      setAllList(res.data);
    });
    // 在组件销毁的时候清除窗口变化事件
    return () => {
      window.onresize = null;
    };
  }, []);

  // 渲染柱状图  传过来是一个对象
  const renderBarView = (obj) => {
    // 基于准备好的dom，初始化echarts实例
    var myChart = Echarts.init(barRef.current);
    // 绘制图表
    myChart.setOption({
      title: {
        text: "新闻分类图示",
      },
      tooltip: {},
      xAxis: {
        data: Object.keys(obj), //X轴所有的键名
        axisLabel: {
          rotate: "45", //页面缩小是让X轴的名字进行斜着展示
          interval: 0, //设置0强制显示，以前是auto
        },
      },
      yAxis: {
        minInterval: 1, //Y的最小间隔是1
      },
      series: [
        {
          name: "数量",
          type: "bar",
          // 把这个数组映射成长度
          data: Object.values(obj).map((item) => item.length),
        },
      ],
    });
    // 给图表进行响应式
    window.onresize = () => {
      myChart.resize();
    };
  };
  // 渲染饼图
  const renderPieView = () => {
    // 把请求回来的所有人发布新闻的数据中，筛选出当前用户发布过的新闻  currentList就是当前登陆的用户
    let currentList = allList.filter((item) => item.author === username);
    // 也同样的对回来的数据进行一个分类装换和排序
    let groupObj = _.groupBy(currentList, (item) => item.category.label);
    // 最后要把数据整理成饼图想要的数据格式
    let list = [];
    for (var i in groupObj) {
      list.push({
        name: i, //key值
        value: groupObj[i].length, //长度
      });
    }
    var myChart;
    // 进行判断是因为每次点击打开都会重新初始化图表实例
    // 警告：react_devtools_backend.js:4026 There is a chart instance already initialized on the dom.
    // 第一次进来当这个值为假时在进行初始化的实例
    if (!pieChart) {
      myChart = Echarts.init(pieRef.current);
      setPieChart(myChart);
    } else {
      myChart = pieChart;
    }
    var option;

    option = {
      title: {
        text: "当前用户新闻分类图示",
        // subtext: 'Fake Data',
        left: "center",
      },
      tooltip: {
        trigger: "item",
      },
      legend: {
        orient: "vertical",
        left: "left",
      },
      series: [
        {
          name: "发布数量",
          type: "pie",
          radius: "50%",
          data: list,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: "rgba(0, 0, 0, 0.5)",
            },
          },
        },
      ],
    };
    // 确保这个option 有值的时候在进行添加option
    option && myChart.setOption(option);
  };

  const {
    username,
    region,
    role: { roleName },
  } = JSON.parse(localStorage.getItem("token"));
  const onClose = () => {
    setOpen(false);
  };
  return (
    <div className="site-card-wrapper">
      <Row gutter={16}>
        <Col span={8}>
          <Card title="用户最常浏览">
            {/* 列表组件 */}
            <List
              size="smll"
              dataSource={viewList} //数据
              renderItem={(item) => (
                // 渲染的数据
                <List.Item>
                  <a href={`/news-manage/preview/${item.id}`}>{item.label}</a>
                </List.Item>
              )}
            ></List>
          </Card>
        </Col>
        <Col span={8}>
          <Card title="点赞最多">
            <List
              size="smll"
              dataSource={startList}
              renderItem={(item) => (
                <List.Item>
                  <a href={`/news-manage/preview/${item.id}`}>{item.label}</a>
                </List.Item>
              )}
            ></List>
          </Card>
        </Col>
        {/* 右侧显示的图片区域 */}
        <Col span={8}>
          <Card
            cover={
              <img
                alt="example"
                src="https://gw.alipayobjects.com/zos/rmsportal/JiqGstEfoWAOHiTxclqi.png"
              />
            }
            actions={[
              <SettingOutlined
                key="setting"
                onClick={() => {
                  setOpen(true);
                  //因为是异步渲染 Dom还没创建出来 放在异步中改为同步处理
                  setTimeout(() => {
                    // 初始化饼图
                    renderPieView();
                  }, 0);
                }}
              />,
              <EditOutlined key="edit" />,
              <EllipsisOutlined key="ellipsis" />,
            ]}
          >
            <Meta
              avatar={<Avatar src="https://joeschmoe.io/api/v1/random" />}
              title={username}
              description={
                <div>
                  <b>{region === "" ? "全球" : region}</b>
                  <span style={{ paddingLeft: "10px" }}>{roleName}</span>
                </div>
              }
            />
          </Card>
        </Col>
      </Row>
      {/* 抽屉效果的饼状图 */}
      <Drawer
        title="个人新闻分类"
        placement="right"
        closable={true} //允许关掉
        onClose={onClose} //关闭
        open={open} //打开
        width="500px"
      >
        <div
          ref={pieRef}
          style={{ width: "100%", height: "400px", marginTop: "30px" }}
        ></div>
      </Drawer>
      {/* 柱状图 */}
      <div
        style={{
          width: "100%",
          height: "400px",
          marginTop: "30px",
          display: "flex",
        }}
      >
        <div ref={barRef} style={{ width: "100%", height: "100%" }}></div>
      </div>
    </div>
  );
}
